//
//  WelcomeViewController.swift
//  ydy_weibo
//
//  Created by 杨德勇 on 16/7/17.
//  Copyright © 2016年 杨德勇. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
class WelcomeViewController: UIViewController {
    
    //背景图片
    private lazy var backImg :UIImageView = UIImageView(image: UIImage(named:"ad_background"))
    //用户头像
    private lazy var iconImg :UIImageView = UIImageView()
    //用户名称
    private lazy var welcomeLabl :UILabel = {
        let l = UILabel()
        l.textColor = UIColor.grayColor()
        l.font = UIFont.systemFontOfSize(19)
        l.textAlignment = .Center
        l.text = (UserAccountViewModel().userName ?? "") + "欢迎回来"
        l.alpha = 0
        l.sizeToFit()
        
        return l
    }()
    //加载视图
    override func loadView() {
        view = backImg
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        

    
    }
    //不能在viewdidload里面做动画
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()
        
    }
    private func setupUI() {
        view.addSubview(iconImg)
        view.addSubview(welcomeLabl)
        
        
        // 设置布局
        iconImg.snp_makeConstraints { (make) in
            make.centerX.equalTo(view.snp_centerX)
            make.bottom.equalTo(view.snp_bottom).offset(-180)
            make.width.equalTo(90)
            make.height.equalTo(90)
            

          
            
        }
        
        welcomeLabl.snp_makeConstraints { (make) in
            make.centerX.equalTo(view.snp_centerX)
            make.top.equalTo(iconImg.snp_bottom).offset(20)
        }
        
        //加载头像
        iconImg.sd_setImageWithURL(UserAccountViewModel().headURL, placeholderImage: UIImage(named: "avatar_default_big"))
        
        //处理头像
        iconImg.layer.cornerRadius = 45
        iconImg.layer.masksToBounds = true
    }
    
    //MARK:-
    //MARK:做动画
    private func startAnimation(){
        //改变约束
        self.iconImg.snp_updateConstraints { (make) in
           make.bottom.equalTo(self.view.snp_bottom).offset(-self.view.bounds.height + 180)
        }
        //执行动画
        
        //usingSpringWithDamping  弹簧系数  0~1之间  越小越弹
        //initialSpringVelocity 加速度
        //弹簧效果 和加速度之间的关系: 弹簧效果 * 10 = 加速度
        
        UIView.animateWithDuration(1.2, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity:9.8, options: [], animations: {
            self.view.layoutIfNeeded()
            }) { (_) in
                //等头像动画执行完成之后
                UIView.animateWithDuration(0.6, animations: { 
                    self.welcomeLabl.alpha = 1
                    }, completion: { (_) in
                        NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: nil)
                })
        }
    }

   
}
